package com.woniuxy.usersecurity.filter;

import com.woniuxy.life.core.config.Payload;
import com.woniuxy.life.core.util.JwtUtils;
import com.woniuxy.usersecurity.config.RsaKeyProperties;
import com.woniuxy.usersecurity.entity.User;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtVerifyFilter extends BasicAuthenticationFilter {

    private RsaKeyProperties prop;

    public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
        super(authenticationManager);
        this.prop = prop;
    }

    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        //System.out.println("请求来源" + request.getServletPath());
        //System.out.println("doFilterInternal+header:" + header);
        if (header == null || !header.startsWith("Bearer ")) {
            //如果携带错误的token，则给用户提示请登录！
            chain.doFilter(request, response);
            return;
        } else {
            //如果携带了正确格式的token要先得到token
            String token = header.replace("Bearer ", "");
            //验证token是否正确，参数一token，参数二，解密公钥，参数三，转换类型
            Payload<User> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), User.class);
            //获取token中的用户信息
            User user = payload.getUserInfo();
            if (user != null) {
                UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authResult);
               // System.out.println("查看用户："+SecurityContextHolder.getContext().getAuthentication());
                super.doFilterInternal(request, response, chain);
               // System.out.println("通过验证");
            }
            //System.out.println("查看用户后："+SecurityContextHolder.getContext().getAuthentication());
        }
    }


}
